/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package presharedkey;

import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 *
 * @author DQ
 */
public class PresharedKey {

    private static final String ALGO = "AES";
    private static final byte[] keyValue =
            new byte[]{'T', 'h', 'e', 'B', 'e', 's', 't',
        'S', 'e', 'c', 'r', 'e', 't', 'K', 'e', 'y'};

    public static String encrypt(String Data) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.ENCRYPT_MODE, key);
        byte[] encVal = c.doFinal(Data.getBytes());
        String encryptedValue = new BASE64Encoder().encode(encVal);
        return encryptedValue;
    }

    public static String decrypt(String encryptedData) throws Exception {
        Key key = generateKey();
        Cipher c = Cipher.getInstance(ALGO);
        c.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);
        String decryptedValue = new String(decValue);
        return decryptedValue;
    }

    private static Key generateKey() throws Exception {
        String test = "1234567890123456";
        byte[] b = new byte[test.length()];
        for(int i=0;i<test.length();i++){
            char temp = test.charAt(i);
            b[i] = (byte) temp;
        }
        //byte [] by = new byte[2];
        ///by[1] = b;
        Key key = new SecretKeySpec(b, ALGO);
        return key;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try {
            
            String password = "my password";
            String passwordEnc = encrypt(password);
            String passwordDec = decrypt(passwordEnc);
            System.out.println("password : "+password);
            System.out.println("Encrypt Password : " + passwordEnc);
            System.out.println("Decrypt Password : " + passwordDec);
        } catch (Exception ex) {
        }

    }
}
